package com.zzzs;

import java.io.IOException;
import java.net.InetAddress;

/**
 * @author zhu_shuai
 * @since 2021/6/26
 */
public class IpScanner {
    private static int timeOut = 150;

    public static void main(String[] args) throws IOException {

        String ip = "192.168.100.15";
        System.out.println(ipStatus(ip, timeOut));
        long num = ipToLong(ip);
        System.out.println(num);
        String s = longToIp(num);
        System.out.println(s);
    }

    private static boolean ipStatus(String ip, int timeOut) throws IOException {
        InetAddress addr = InetAddress.getByName(ip);
        // timeOut为等待时间(毫秒)
        return addr.isReachable(timeOut);
    }

    /**
     * 将ip地址转换为long
     */
    public static long ipToLong(String ip){
        String[] split = ip.split("\\.");
        long num = 0L;
        for (int i = 0; i < split.length; i++) {
            // 将一段ip转换为整型
            long ip1 = Long.parseLong(split[i]);
            num = ( ip1 << 8 * (3 -i) ) | num;
        }
        return num;
    }

    public static String longToIp(long num)
    {
        String[] ipArray = new String[4];
        for (int i = 0; i < 4; i++) {
            long l = num & (255 << 8 * i);
            ipArray[3-i] = String.valueOf(l >>> 8 * i);
        }
        return String.join(".", ipArray);
    }


}
